package org.budo.mongo.jdbc.driver.resultset;

import java.sql.SQLException;

import org.bson.Document;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcResultSet;

import com.mongodb.client.MongoCursor;

/**
 * 数据从MongoCursor中读取
 * 
 * @author li
 */
public class MongoCursorResultSet extends BudoMongoJdbcResultSet {
    private MongoCursor<Document> mongoCursor;

    private Document nextDocument;

    private Integer rowIndex = 0;

    /* default */ Document getNextDocument() {
        return nextDocument;
    }

    public void setNextDocument(Document nextDocument) {
        this.nextDocument = nextDocument;
    }

    public void setMongoCursor(MongoCursor<Document> mongoCursor) {
        this.mongoCursor = mongoCursor;
    }

    public void close() throws SQLException {
        mongoCursor.close();
    }

    public boolean next() throws SQLException {
        if (this.rowIndex < 1 && null != this.nextDocument) {
            this.rowIndex++;
            return true;
        }

        if (mongoCursor.hasNext()) {
            this.rowIndex++;
            this.nextDocument = mongoCursor.next();
            return true;
        }

        return false;
    }

    public Object getObject(String columnLabel) throws SQLException {
        Object value = this.getNextDocument().get(columnLabel);
        if (null == value) {
            this.setLastGotValueWasNull(true);
        }
        return value;
    }
}